package com.hyfrogx.modules.operation.service.umeng;

import com.hyfrogx.common.log.LogEnum;
import com.hyfrogx.common.log.LogUtils;
import com.hyfrogx.common.utils.Terminal;
import com.hyfrogx.modules.operation.entity.HyAppPushEntity;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;
import org.slf4j.Logger;

import java.io.BufferedReader;
import java.io.InputStreamReader;

public class PushClient {

	// The user agent
	protected final String USER_AGENT = "Mozilla/5.0";

	// This object is used for sending the post request to Umeng
	protected HttpClient client = new DefaultHttpClient();

	// The host
	protected static final String host = "http://msg.umeng.com";

	// The upload path
	protected static final String uploadPath = "/upload";

	// The post path
	protected static final String postPath = "/api/send";

	// The upload path
	protected static final String canclePath = "/api/cancel";

	// The upload path
	protected static final String status = "/api/status";

	Logger UMENG_LOG = LogUtils.Logger(LogEnum.UMENG_LOGS);

	/**
	 * 发送推送
	 * 
	 * @param msg
	 * @return
	 * @throws Exception
	 */
	public boolean send(UmengNotification msg, HyAppPushEntity appPush) throws Exception {
		UMENG_LOG.info("发送推送接口-----------------------------");
		String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
		msg.setPredefinedKeyValue("timestamp", timestamp);
		String url = host + postPath;
		String postBody = msg.getPostBody();
		UMENG_LOG.info("postBody:"+postBody);
		if (appPush.getDisplayChannel().intValue() !=  Terminal.DisplayChannel.ios ){
			/**
			 * 小米华为需要修改字段消息体
			 */
			JSONObject jsonObject = new JSONObject();
			jsonObject.put("mipush", "true");
			jsonObject.put("mi_activity", "com.heyoo.fxw.baseapplication.main.activitys.MipushTestActivity");
			String date = jsonObject.toString().substring(1, jsonObject.toString().length()-1);
			postBody = msg.getPostBody().substring(0, msg.getPostBody().length()-1)+","+date+"}";
		}
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
		UMENG_LOG.info("sin:"+sign);
		url = url + "?sign=" + sign;
		UMENG_LOG.info("URL:"+url);
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response
		HttpResponse response = client.execute(post);
		UMENG_LOG.info("发送推送---------------post请求："+post.toString());
		UMENG_LOG.info("HttpResponse："+response.toString());
		int status = response.getStatusLine().getStatusCode();
		// System.out.println("Response Code : " + status);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		UMENG_LOG.info("RESULT:"+result.toString());
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject respJson = new JSONObject(result.toString());
 		JSONObject data = respJson.getJSONObject("data");
		UMENG_LOG.info("data数据："+data.toString());
		if (status == 200) {
			String ret = respJson.getString("ret");
			if (ret.equals("SUCCESS")){
				String task_id = null;
				if (data.toString().contains("task_id")){
					task_id = data.getString("task_id");
					UMENG_LOG.info("发送成功，task_id:"+task_id);
				}else{
					task_id = data.getString("msg_id");
					UMENG_LOG.info("发送成功，msg_id:"+task_id);
				}
				appPush.setTaskId(task_id);
				return true;
			}else{
				String error_code = data.getString("error_code");
				appPush.setTaskId("error_code:" + error_code);
				UMENG_LOG.info("发送失败，error_code"+error_code);
				return false;
			}
		} else {
			String error_code = data.getString("error_code");
			appPush.setTaskId("error_code:" + error_code);
			UMENG_LOG.info("发送失败，error_code"+error_code);
			return false;
		}

	}
	public boolean sendIos(UmengNotification msg) throws Exception {
		String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
		msg.setPredefinedKeyValue("timestamp", timestamp);
		String url = host + postPath;
		String postBody = msg.getPostBody();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + msg.getAppMasterSecret()).getBytes("utf8"));
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response
		HttpResponse response = client.execute(post);
		int status = response.getStatusLine().getStatusCode();
		// System.out.println("Response Code : " + status);
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject respJson = new JSONObject(result.toString());
		JSONObject data = respJson.getJSONObject("data");
		if (status == 200) {
			String ret = respJson.getString("ret");
			if (ret.equals("SUCCESS")){
				String task_id = null;
				if (data.toString().contains("task_id")){
					task_id = data.getString("task_id");
				}else{
					task_id = data.getString("msg_id");
				}
				return true;
			}else{
				String error_code = data.getString("error_code");
				String error_msg = data.getString("error_msg");
				return false;
			}
		} else {
			String error_code = data.getString("error_code");
			return false;
		}
	}
	/**
	 * 未用到
	 * @param appkey
	 * @param appMasterSecret
	 * @param contents
	 * @return
	 * @throws Exception
	 */
	// Upload file with device_tokens to Umeng
	public String uploadContents(String appkey, String appMasterSecret, String contents) throws Exception {
		// Construct the json string
		JSONObject uploadJson = new JSONObject();
		uploadJson.put("appkey", appkey);
		String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
		uploadJson.put("timestamp", timestamp);
		uploadJson.put("content", contents);
		// Construct the request
		String url = host + uploadPath;
		String postBody = uploadJson.toString();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response
		HttpResponse response = client.execute(post);
		// System.out.println("Response Code : " +
		// response.getStatusLine().getStatusCode());
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		// System.out.println(result.toString());
		// Decode response string and get file_id from it
		JSONObject respJson = new JSONObject(result.toString());
		String ret = respJson.getString("ret");
		if (!ret.equals("SUCCESS")) {
			throw new Exception("Failed to upload file");
		}
		JSONObject data = respJson.getJSONObject("data");
		String fileId = data.getString("file_id");
		// Set file_id into rootJson using setPredefinedKeyValue

		return fileId;
	}

	/**
	 * 取消任务
	 * 
	 * @param appkey
	 * @param appMasterSecret
	 * @return
	 * @throws Exception
	 */
	public boolean cancle(HyAppPushEntity appPush, String appkey, String appMasterSecret) throws Exception {
		JSONObject uploadJson = new JSONObject();
		uploadJson.put("appkey", appkey);
		String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
		uploadJson.put("timestamp", timestamp);
		uploadJson.put("task_id", appPush.getTaskId());
		String url = host + canclePath;
		String postBody = uploadJson.toString();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response
		HttpResponse response = client.execute(post);
		// System.out.println("Response Code : " +
		// response.getStatusLine().getStatusCode());
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject respJson = new JSONObject(result.toString());
		JSONObject data = respJson.getJSONObject("data");
		int status = response.getStatusLine().getStatusCode();
		if (status == 200) {
			String ret = respJson.getString("ret");
			if (ret.equals("SUCCESS")){
				return true;
			}else{
				String error_code = data.getString("error_code");
				throw new Exception(
						"取消失败;错误码:" + error_code + ".请去http://dev.umeng.com/sdk_integate/android_push_apidoc#4_8查询");
			}
		} else {
			throw new Exception("取消任务失败");
		}
	}

	/**
	 * 查询任务状态
	 * 
	 * @param taskId
	 * @param appkey
	 * @param appMasterSecret
	 * @return
	 */
	public int checkBroadcastStatus(String taskId, String appkey, String appMasterSecret) throws Exception {
		JSONObject uploadJson = new JSONObject();
		uploadJson.put("appkey", appkey);
		String timestamp = Integer.toString((int) (System.currentTimeMillis() / 1000));
		uploadJson.put("timestamp", timestamp);
		uploadJson.put("task_id", taskId);
		String url = host + status;
		String postBody = uploadJson.toString();
		String sign = DigestUtils.md5Hex(("POST" + url + postBody + appMasterSecret).getBytes("utf8"));
		url = url + "?sign=" + sign;
		HttpPost post = new HttpPost(url);
		post.setHeader("User-Agent", USER_AGENT);
		StringEntity se = new StringEntity(postBody, "UTF-8");
		post.setEntity(se);
		// Send the post request and get the response
		HttpResponse response = client.execute(post);
		// System.out.println("Response Code : " +
		// response.getStatusLine().getStatusCode());
		BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		StringBuffer result = new StringBuffer();
		String line = "";
		while ((line = rd.readLine()) != null) {
			result.append(line);
		}
		JSONObject respJson = new JSONObject(result.toString());
		JSONObject data = respJson.getJSONObject("data");
		int status = response.getStatusLine().getStatusCode();
		
		if (status == 200) {
			String ret = respJson.getString("ret");
			if (ret.equals("SUCCESS")){
				return data.getInt("status");
			}else{
				String error_code = data.getString("error_code");
				throw new Exception(
						"查询状态失败;错误码:" + error_code + ".请去http://dev.umeng.com/sdk_integate/android_push_apidoc#4_8查询");
			}
		} else {
			throw new Exception("查询状态失败");
		}
	}
}
